package com.mgface.springdata.controller;

import com.mgface.springdata.entity.Article;
import com.mgface.springdata.repository.ArticleRepository;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project springdataCollection
 * @create 2018-08-18 23:30
 **/
@RestController
public class ESController {
    @Autowired
    private ArticleRepository repository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping("/get")
    public List<Article> get() {
        //analyzer:指定分词器，如果实体指定，则可以忽略
        QueryBuilder query = QueryBuilders.queryStringQuery("中").field("content");
        Page<Article> result = repository.search(query, new PageRequest(0, 10));
        return result.getContent();
    }
    @GetMapping("/getTemplate")
    public void getTemplate(){
        SearchQuery query =  new NativeSearchQueryBuilder().withQuery(QueryBuilders.queryStringQuery("中"))
                .withFilter(QueryBuilders.queryStringQuery("国")).withPageable(new PageRequest(0,10))
                .withIndices("book").build();
        AggregatedPage<Article> results = elasticsearchTemplate.queryForPage(query, Article.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                List<Article> content = new ArrayList<>();
                for(SearchHit hit : searchResponse.getHits()){
                    Article entity = new Article();
                    entity.setContent(hit.getSource().get("content").toString());
                    content.add(entity);
                }
                return new AggregatedPageImpl<T>((List<T>)content,pageable,searchResponse.getHits().getHits().length);
            }
        });
        results.forEach(e-> System.out.println(e.getContent()));
    }
}
